package org.robert.export_client.easyexcel.read.impl;

import com.alibaba.excel.EasyExcel;
import com.robert.common.commonutil.exception.AppException;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.robert.export_client.aop.ExcelDictAdapter;
import org.robert.export_client.easyexcel.read.entity.ExcelReadRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description 读取excel文件，返回集合
 * @Author robert
 * @Date 2024/1/13 22:39
 **/
@Slf4j
@Data
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = true)
public class ExcelRead<T> extends ExcelReadRequest<T>{


    public ExcelRead(Class<T> clazz) {
        this.clazz = clazz;
    }

    public ExcelRead(Class<T> clazz, Map<String, Map<String, String>> dictMap) {
        this.clazz = clazz;
        this.dictMap = dictMap;
        if(MapUtils.isNotEmpty(dictMap)){
            this.checker = new ExcelDictAdapter<T>();
        }
    }

    public ExcelRead(String path, Class<T> clazz) {
        this.path = path;
        this.clazz = clazz;
    }
    public ExcelRead(String path, Class<T> clazz, Map<String, Map<String, String>> dictMap) {
        this.path = path;
        this.clazz = clazz;
        this.dictMap = dictMap;
        if(MapUtils.isNotEmpty(dictMap)){
            this.checker = new ExcelDictAdapter<T>();
        }
    }

    /**
     * web上传读取
     * @throws IOException
     */
    public List<T> read(MultipartFile file) throws IOException {
        if(!this.check() || file == null){
            throw new AppException("500", "参数异常");
        }
        List<T> list = EasyExcel.read(file.getInputStream()).head(this.clazz).sheet().doReadSync();
        if(MapUtils.isNotEmpty(dictMap)){
            checker.setDict(list, dictMap);
        }
        return list;
    }
    /**
     * 磁盘读取
     */
    public List<T> read() {
        if(!this.check() || StringUtils.isBlank(path)){
            throw new AppException("500", "参数异常");
        }
        List<T> list = EasyExcel.read(path).head(this.clazz).sheet().doReadSync();
        if(MapUtils.isNotEmpty(dictMap)){
            checker.setDict(list, dictMap);
        }
        return list;
    }

}
